import 'package:flutter/material.dart';
import '../core/gitcode_api.dart';
import '../core/app_config.dart';
import '../core/app_theme.dart';
import 'dart:async';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final _keywordController = TextEditingController();
  final _tokenController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  final _client = GitCodeApiClient();

  QueryMode _mode = QueryMode.user;
  List<GitCodeSearchUser> _userResults = const [];
  List<GitCodeRepository> _repoResults = const [];
  String? _errorMessage;
  bool _isLoading = false;
  bool _isLoadingMore = false;
  int _currentPage = 1;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _tokenController.text = AppConfig.demoToken;
  }

  @override
  void dispose() {
    _keywordController.dispose();
    _tokenController.dispose();
    super.dispose();
  }

  Future<void> _performSearch() async {
    if (_isLoading) return;
    if (!_formKey.currentState!.validate()) return;

    FocusScope.of(context).unfocus();

    setState(() {
      _isLoading = true;
      _errorMessage = null;
      _userResults = const [];
      _repoResults = const [];
      _currentPage = 1;
      _hasMore = true;
    });

    final token = _tokenController.text.trim();

    try {
      if (_mode == QueryMode.user) {
        final users = await _client.searchUsers(
          keyword: _keywordController.text,
          personalToken: token,
          perPage: 8,
          page: 1,
        );
        setState(() {
          _userResults = users;
          _hasMore = users.length == 8;
          _currentPage = 2;
        });
      } else {
        final repos = await _client.searchRepositories(
          keyword: _keywordController.text,
          personalToken: token,
          perPage: 8,
          page: 1,
        );
        setState(() {
          _repoResults = repos;
          _hasMore = repos.length == 8;
          _currentPage = 2;
        });
      }
    } on GitCodeApiException catch (error) {
      setState(() {
        _errorMessage = error.message;
      });
    } catch (error) {
      setState(() {
        _errorMessage = '未知错误：$error';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _loadMore() async {
    if (_isLoadingMore || !_hasMore || _keywordController.text.trim().isEmpty) {
      return;
    }

    setState(() {
      _isLoadingMore = true;
    });

    final token = _tokenController.text.trim();

    try {
      if (_mode == QueryMode.user) {
        final moreUsers = await _client.searchUsers(
          keyword: _keywordController.text,
          personalToken: token,
          perPage: 8,
          page: _currentPage,
        );
        setState(() {
          _userResults.addAll(moreUsers);
          _hasMore = moreUsers.length == 8;
          _currentPage++;
        });
      } else {
        final moreRepos = await _client.searchRepositories(
          keyword: _keywordController.text,
          personalToken: token,
          perPage: 8,
          page: _currentPage,
        );
        setState(() {
          _repoResults.addAll(moreRepos);
          _hasMore = moreRepos.length == 8;
          _currentPage++;
        });
      }
    } on GitCodeApiException catch (error) {
      setState(() {
        _errorMessage = error.message;
      });
    } catch (error) {
      setState(() {
        _errorMessage = '未知错误：$error';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isLoadingMore = false;
        });
      }
    }
  }

  Future<void> _refresh() async {
    // 重置搜索状态
    setState(() {
      _userResults = const [];
      _repoResults = const [];
      _isLoading = false;
      _isLoadingMore = false;
      _errorMessage = null;
      _keywordController.clear();
      _currentPage = 1;
      _hasMore = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GitCode 口袋工具'),
        elevation: 4,
      ),
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: SafeArea(
          child: SingleChildScrollView(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                _buildIntro(),
                const SizedBox(height: 20),
                _buildFormCard(),
                const SizedBox(height: 20),
                _buildResultSection(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildIntro() {
    return const Text(
      '输入关键字 + access token，立即查询 GitCode 用户或仓库（搜索接口需授权）。',
      style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
    );
  }

  Widget _buildFormCard() {
    return Card(
      elevation: 0,
      clipBehavior: Clip.antiAlias,
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              _buildModeSwitcher(),
              const SizedBox(height: 12),
              TextFormField(
                controller: _keywordController,
                textInputAction: TextInputAction.search,
                decoration: InputDecoration(
                  labelText: '搜索关键字',
                  hintText: '例如：iflytek / spark',
                  prefixIcon: const Icon(Icons.search),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(24),
                  ),
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding:
                      const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(24),
                    borderSide: const BorderSide(
                        color: AppTheme.primaryColor, width: 2),
                  ),
                ),
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '请输入关键字';
                  }
                  return null;
                },
                onFieldSubmitted: (_) => _performSearch(),
              ),
              const SizedBox(height: 12),
              TextFormField(
                controller: _tokenController,
                decoration: InputDecoration(
                  labelText: 'Access Token',
                  hintText: 'GitCode 个人设置 > Access Token',
                  prefixIcon: const Icon(Icons.vpn_key_outlined),
                ),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.trim().isEmpty) {
                    return '搜索接口需提供 access token';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),
              FilledButton.icon(
                onPressed: _isLoading ? null : _performSearch,
                icon: _isLoading
                    ? const SizedBox(
                        width: 18,
                        height: 18,
                        child: CircularProgressIndicator(strokeWidth: 2),
                      )
                    : const Icon(Icons.play_arrow_rounded),
                label: Text(_isLoading ? '查询中...' : '查询'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildResultSection() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return ListView(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        children: [
          Center(
            child: Padding(
              padding: const EdgeInsets.all(32),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.error_outline,
                      size: 48, color: AppTheme.errorColor),
                  const SizedBox(height: 16),
                  Text(
                    _errorMessage!,
                    textAlign: TextAlign.center,
                    style: TextStyle(color: AppTheme.textSecondary),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: _performSearch,
                    child: const Text('重试'),
                  ),
                ],
              ),
            ),
          ),
        ],
      );
    }

    if (_mode == QueryMode.user) {
      return _buildUserResults();
    }
    return _buildRepositoryResults();
  }

  Widget _buildModeSwitcher() {
    return SegmentedButton<QueryMode>(
      segments: const [
        ButtonSegment(
          value: QueryMode.user,
          icon: Icon(Icons.person_outline),
          label: Text('用户'),
        ),
        ButtonSegment(
          value: QueryMode.repository,
          icon: Icon(Icons.bookmark_outline),
          label: Text('仓库'),
        ),
      ],
      selected: <QueryMode>{_mode},
      onSelectionChanged: (selection) {
        final next = selection.first;
        if (next != _mode) {
          setState(() {
            _mode = next;
            _errorMessage = null;
            _userResults = const [];
            _repoResults = const [];
          });
        }
      },
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.resolveWith<Color>((states) {
          if (states.contains(MaterialState.selected)) {
            return AppTheme.primaryColor;
          }
          return Colors.white;
        }),
        foregroundColor: MaterialStateProperty.resolveWith<Color>((states) {
          if (states.contains(MaterialState.selected)) {
            return Colors.white;
          }
          return AppTheme.textSecondary;
        }),
        shape: MaterialStateProperty.all(
          RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        ),
      ),
    );
  }

  Widget _buildUserResults() {
    if (_userResults.isEmpty) {
      return const _InfoBanner(
        icon: Icons.info_outline,
        background: Color(0xFFEFF4FF),
        textColor: Color(0xFF1A237E),
        message: '暂无数据，输入关键字并点击“查询”试试。',
      );
    }

    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        if (notification is ScrollEndNotification &&
            notification.metrics.extentAfter == 0 &&
            _hasMore &&
            !_isLoadingMore) {
          _loadMore();
        }
        return true;
      },
      child: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        child: Column(
          children: [
            ..._userResults.map(_UserTile.new),
            if (_hasMore)
              _isLoadingMore
                  ? const Padding(
                      padding: EdgeInsets.all(16),
                      child: CircularProgressIndicator(),
                    )
                  : const SizedBox()
          ],
        ),
      ),
    );
  }

  Widget _buildRepositoryResults() {
    if (_repoResults.isEmpty) {
      return const _InfoBanner(
        icon: Icons.info_outline,
        background: Color(0xFFEFF4FF),
        textColor: Color(0xFF1A237E),
        message: '还没有结果，输入关键字并点击查询即可获取仓库列表。',
      );
    }

    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        if (notification is ScrollEndNotification &&
            notification.metrics.extentAfter == 0 &&
            _hasMore &&
            !_isLoadingMore) {
          _loadMore();
        }
        return true;
      },
      child: SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        child: Column(
          children: [
            ..._repoResults.map(_RepoTile.new),
            if (_hasMore)
              _isLoadingMore
                  ? const Padding(
                      padding: EdgeInsets.all(16),
                      child: CircularProgressIndicator(),
                    )
                  : const SizedBox()
          ],
        ),
      ),
    );
  }
}

enum QueryMode { user, repository }

class _InfoBanner extends StatelessWidget {
  const _InfoBanner({
    required this.icon,
    required this.background,
    required this.textColor,
    required this.message,
  });

  final IconData icon;
  final Color background;
  final Color textColor;
  final String message;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: background,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(icon, color: textColor),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              message,
              style: Theme.of(context)
                  .textTheme
                  .bodyMedium
                  ?.copyWith(color: textColor),
            ),
          ),
        ],
      ),
    );
  }
}

class _UserTile extends StatelessWidget {
  const _UserTile(this.user);

  final GitCodeSearchUser user;

  @override
  Widget build(BuildContext context) {
    final title = user.name?.isNotEmpty == true ? user.name! : user.login;
    final subtitleParts = <String>[
      '@${user.login}',
      if (user.createdAt != null) '注册 ${user.createdAt}',
    ];

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
      child: ListTile(
        leading: CircleAvatar(
          backgroundImage: NetworkImage(user.avatarUrl),
          onBackgroundImageError: (_, __) {},
          backgroundColor: AppTheme.surfaceColor,
          radius: 24,
        ),
        title: Text(title, style: const TextStyle(fontWeight: FontWeight.bold)),
        subtitle: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              subtitleParts.join(' · '),
              style: const TextStyle(fontSize: 12),
            ),
            if (user.htmlUrl != null)
              Text(
                user.htmlUrl!,
                style: const TextStyle(fontSize: 12, color: Colors.blue),
              ),
          ],
        ),
        contentPadding:
            const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      ),
    );
  }
}

class _RepoTile extends StatelessWidget {
  const _RepoTile(this.repo);

  final GitCodeRepository repo;

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      elevation: 2,
      shadowColor: const Color.fromRGBO(0, 0, 0, 0.1),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: const Color(0x1A4361EE),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Icon(Icons.folder_outlined,
                      size: 24, color: AppTheme.primaryColor),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    repo.fullName,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            if (repo.description?.isNotEmpty == true)
              Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: Text(
                  repo.description!,
                  style: TextStyle(color: AppTheme.textSecondary),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            Wrap(
              spacing: 8,
              runSpacing: 4,
              children: [
                if (repo.language != null)
                  _StatChip(label: '语言', valueLabel: repo.language),
                _StatChip(label: 'Star', value: repo.stars),
                _StatChip(label: 'Fork', value: repo.forks),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              '更新 ${repo.updatedAt ?? '-'}',
              style: const TextStyle(fontSize: 12),
            ),
            Text(
              repo.webUrl,
              style: const TextStyle(fontSize: 12, color: Colors.blue),
            ),
          ],
        ),
      ),
    );
  }
}

class _StatChip extends StatelessWidget {
  const _StatChip({
    required this.label,
    this.value,
    this.valueLabel,
  });

  final String label;
  final int? value;
  final String? valueLabel;

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    final display = valueLabel ?? (value ?? 0).toString();
    return Chip(
      label: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            display,
            style: textTheme.titleMedium,
          ),
          Text(label, style: textTheme.bodySmall),
        ],
      ),
    );
  }
}
